<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row :gutter="90">
        <el-col :span="15">
          <el-form
            ref="form"
            :model="user"
            label-width="80px"
            :rules="userFormRules"
          >
            <el-form-item label="编号">
              {{ user.id }}
            </el-form-item>
            <el-form-item label="手机"> {{ user.mobile }} </el-form-item>
            <el-form-item label="媒体名称" prop="name">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍" prop="intro">
              <el-input v-model="user.intro" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" type="email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="updateUser()"
                :loading="updateLoading"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="9">
          <label for="file" >
            <el-avatar
              shape="square"
              :size="150"
              fit="cover"
              :src="user.photo"
            ></el-avatar>
            <p>点击修改头像</p>
          </label>
          <input
            type="file"
            id="file"
            hidden
            @change="onFileChange"
            ref="file"
          />
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      width="30%"
      @opened="onDialogOpened()"
      @close="onDialogClose()"
    >
      <div class="preview-image">
        <img :src="previewImage" alt="" ref="img" />
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onUpdatePhoto"
          :loading="updatePhotoLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserProfile, updateUserPhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import globalBus from '@/utils/global-bus'

export default {
  name: 'SettingIndex',
  data() {
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      user: {
        email: '',
        id: null,
        intro: '',
        mobile: '',
        name: '',
        photo: ''
      },
      dialogVisible: false,
      previewImage: '',
      updateLoading: false,
      cropper: null,
      updatePhotoLoading: false,
      userFormRules: {
        name: [
          { required: true, message: '请输入名称（1~7位）', trigger: 'blur' },
          {
            require: true,
            min: 1,
            max: 7,
            message: '长度在 1 到 7 个字符',
            trigger: 'change'
          }
        ],
        intro: [
          {
            require: true,
            min: 0,
            max: 60,
            message: '长度在 0 到 60 个字符',
            trigger: 'change'
          }
        ],
        email: [
          {
            validator: checkEmail,
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.loadUser()
  },
  methods: {
    loadUser() {
      getUserProfile().then((res) => {
        this.user = res.data.data
      })
    },
    onFileChange() {
      const file = this.$refs.file
      const blobData = window.URL.createObjectURL(file.files[0])
      this.previewImage = blobData
      this.dialogVisible = true
      this.$refs.file.value = '' // 解决选择相同文件不触发change事件的问题
    },
    onDialogOpened() {
      const image = this.$refs.img
      this.cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 1,
        dragMode: 'move',
        cropBoxMovable: true,
        // cropBoxResizable: false,
        // background: false,
        movable: true
      })
    },
    onDialogClose() {
      // 另一种方式 cropper.replace('新的图片url')
      // 关闭对话框，销毁裁切器
      this.cropper.destroy()
    },
    onUpdatePhoto() {
      this.updatePhotoLoading = true
      this.cropper.getCroppedCanvas().toBlob((file) => {
        const fd = new FormData()
        fd.append('photo', file)
        updateUserPhoto(fd)
          .then((res) => {
            this.$message.success('更新头像成功！')
            this.dialogVisible = false
            this.user.photo = window.URL.createObjectURL(file)
            globalBus.$emit('update-user-photo', this.user)
            this.updatePhotoLoading = false
          })
          .catch(() => {
            this.$message.error('更新头像失败！')
            this.updatePhotoLoading = false
          })
      })
    },
    updateUser() {
      this.updateLoading = true
      updateUserProfile({
        name: this.user.name,
        intro: this.user.intro,
        email: this.user.email
      })
        .then((res) => {
          this.updateLoading = false
          this.$message.success('保存成功！')
          globalBus.$emit('update-user', this.user)
        })
        .catch(() => {
          this.$message.error('保存失败！')
        })
    }
  }
}
</script>
<style lang="less" scoped>
.preview-image {
  img {
    display: block;
    max-width: 100%;
    height: 150px;
  }
}
</style>
